<?php
/**
 * This file is part of DomAr.
 * 
 * DomAr is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * DomAr is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with DomAr.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @link http://inditel.ee/
 * @copyright 2007-2009 Inditel Meedia OÜ
 * @author Oliver Leisalu <oliver@inditel.ee>
 */
 
/**
* @internal
* @package DomAr
*/
class DomArTable extends DomSqlTable {
	
	/**
	* @param String DomArObject classname which table is handled.
	*/
	protected $className;
	
	private static $tables = array();
	
	private $indexes = array();
	

	public function __construct( $className ) {
		$this->className = $className;
		parent::__construct( call_user_func(array($className,'getTableName')) );
		$this->setDatabase( call_user_func(array($className,'getDatabase')) );
		self::$tables[$className] = $this;
	}
	
	public static function get( $className ) {
		if( !self::$tables[$className] )
			self::$tables[$className] = new DomArTable( $className );
		return self::$tables[$className];
	}
	
	public function addClassIndex( $type, array $columns ) {
		$this->indexes[] = array('type' => $type, 'columns' => $columns);
	}
	
	/**
	* @return Boolean true if table was changed or created
	*/
	public function update() {
	
		static $updated;
		static $starter;
		static $s;
		$id = $s++;
		
		if( $starter == NULL ) {
			$starter = $id;
		}

		if( $updated[$this->className] != true ) {
			$updated[$this->className] = true;
			// create table.
			$re1 = parent::update();
			$re2 = call_user_func( array($this->className, '_updateTableFields') );
			
			foreach( $this->indexes as $index ) {
				$name = 'ci_'.implode('_',$index['columns']);
				$this->changeIndex( $name, $index['columns'], $index['type']);
			}
		}
		
		if( $id == $starter ) {
			$updated = array();
			$starter = NULL;
		}
		
		return $re1 or $re2;
	}
	
	public function create() {
		try {
			$mquery  = 'CREATE TABLE '.$this->getDbTable().' ( 
							id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
							className VARCHAR(50) NOT NULL
						) ENGINE='.$this->engine.' CHARACTER SET '.$this->characterSet.' COLLATE '.$this->characterCollate;
			DomSql::query( $mquery, $this->connectionAlias );
			
			return false;
		} catch( RuntimeException $e ) {
			if( $e->getCode() != 1050 ) {
				throw $e;
			}
			return true;
		}
	}

}
?>